package cfg

import (
	"gitee.com/whilew/gmodel/internal/util"
	"sync"
)

func GetGlobalEnv() (map[string]string, error) {
	file, err := EnvFile(true)
	if err != nil {
		return nil, err
	}
	return getEnvFile(file)
}

func GetProjectEnv() (map[string]string, error) {
	file, err := EnvFile(false)
	if err != nil {
		return nil, err
	}
	return getEnvFile(file)
}

var (
	_cfg map[string]string
	o    sync.Once
	e    error
)

func GetEnv() (map[string]string, error) {
	o.Do(func() {
		g, err := GetGlobalEnv()
		if err != nil {
			e = err
			return
		}
		p, err := GetProjectEnv()
		if err != nil {
			e = err
			return
		}
		for k, v := range p {
			g[k] = v
		}
		_cfg = g
	})
	return _cfg, e
}

func GetCfg(key string) string {
	env, err := GetEnv()
	if err != nil {
		util.Fatalf("gmodel: %v", err)
	}
	return env[key]
}
